//
//  AFAppDotNetAPIClient.m
//  LiHai
//
//  Created by YAO on 15/4/15.
//  Copyright (c) 2015年 YAO. All rights reserved.
//

#import "CitydoCheckAFAppDotNetAPIClient.h"
#import "CitydoCheckUrlManage.h"
#import "CitydoCheckSecurityUtil.h"

#import<CommonCrypto/CommonDigest.h>
#import "CitydoCheckAuthorization.h"
#import "CitydoCheckJDDeviceUtils.h"
#import "UIDevice+CityDOFCUUID.h"


@interface CitydoCheckAFAppDotNetAPIClient ()

+ (instancetype)sharedClient;

@end

@implementation CitydoCheckAFAppDotNetAPIClient


+ (instancetype)sharedClient {
    
    static dispatch_once_t once;
    static CitydoCheckAFAppDotNetAPIClient *sharedView;
    dispatch_once(&once, ^ {
        sharedView = [[self alloc] initWithBaseURL:[NSURL URLWithString:
                                                    [CitydoCheckUrlManage sharedManager].baseUrl]];
    });
    return sharedView;
}

+ (instancetype)sharedSenseTimeClient {
    
    static dispatch_once_t once;
    static CitydoCheckAFAppDotNetAPIClient *sharedView;
    dispatch_once(&once, ^ {
        sharedView = [[self alloc] initWithSenseTimeBaseURL:[NSURL URLWithString:
                                                             [CitydoCheckUrlManage sharedManager].baseUrl]];
    });
    return sharedView;
}



#pragma mark - header封装
- (instancetype)initWithBaseURL:(NSURL *)url {
    
    self = [super initWithBaseURL:url];
    if (self) {
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        
        self.responseSerializer = [AFJSONResponseSerializer serializer];
        
        self.responseSerializer=[AFHTTPResponseSerializer serializer];
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/xml",
                                                          @"text/html",
                                                          @"text/json",
                                                          @"text/javascript",
                                                          @"text/plain",
                                                          @"text/json",
                                                          nil];
        self.requestSerializer.timeoutInterval = 30.0;
        [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
        [self.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

        
        NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
//        NSString *strIDFV = [SAMKeychain passwordForService:bundleIdentifier account:@"strIDFV"];
//
//        if (strIDFV == nil) {
//            strIDFV = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
//            [SAMKeychain setPassword:strIDFV forService:bundleIdentifier account:@"strIDFV"];
//        }
        
        NSString *udid  = [[UIDevice currentDevice] uuid];
        if (udid== nil) {
            udid = @"";
        }
        NSString *iphoneType = [CitydoCheckJDDeviceUtils deviceTypeStr];
        NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        NSString *appVersionCode = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        NSString *appNameChinese = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
        [self.requestSerializer setValue:appNameChinese forHTTPHeaderField:@"appNameChinese"];
        [self.requestSerializer setValue:appVersionCode forHTTPHeaderField:@
         "appVersionCode"];
        [self.requestSerializer setValue:appVersion forHTTPHeaderField:@"appVersion"];
        [self.requestSerializer setValue:bundleIdentifier forHTTPHeaderField:@"bundleIdentifier"];
        [self.requestSerializer setValue:udid forHTTPHeaderField:@"deviceid"];
        [self.requestSerializer setValue:@"office" forHTTPHeaderField:@"appname"];
        [self.requestSerializer setValue:iphoneType forHTTPHeaderField:@"iphoneType"];
        //CitydoCheckAuthorization
        NSDictionary *params = [CitydoCheckAuthorization encodeParams];
        [self.requestSerializer setValue:params[@"API_KEY"] forHTTPHeaderField:@"APIKEY"];
        [self.requestSerializer setValue:params[@"timestamp"] forHTTPHeaderField:@"timestamp"];
        [self.requestSerializer setValue:params[@"nonce"] forHTTPHeaderField:@"nonce"];
        [self.requestSerializer setValue:params[@"signature"] forHTTPHeaderField:@"signature"];
        [self.requestSerializer setValue:params[@"API_SECRET"] forHTTPHeaderField:@"APISECRET"];

    }
    return self;
}

#pragma mark - header封装
- (instancetype)initWithSenseTimeBaseURL:(NSURL *)url {
    
    self = [super initWithBaseURL:url];
    if (self) {
        //                self.requestSerializer = [AFJSONRequestSerializer serializer];
        //
        //                self.responseSerializer = [AFJSONResponseSerializer serializer];
        //
        //                self.responseSerializer=[AFHTTPResponseSerializer serializer];
        //        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/xml",
        //                                                          @"text/html",
        //                                                          @"text/json",
        //                                                          @"text/javascript",
        //                                                          @"text/plain",
        //                                                          @"text/json",
        //                                                          nil];
        self.requestSerializer.timeoutInterval = 30.0;
        //                [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
        //                [self.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        
        
        [self.requestSerializer setValue:[CitydoCheckAuthorization encode] forHTTPHeaderField:@"Authorization"];
    }
    return self;
}

#pragma mark - get请求
+ (void)getAsynchronous:(NSString *)path
              parameter:(NSDictionary *)dic
           successBlock:(HTTPRequestFinishingHandler)successBlock
             errorBlock:(HTTPRequestFailedHandler)errorBlock {
    
    [[self sharedClient] GET:path parameters:dic progress:nil
                     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                         
                         NSDictionary *dict = [[self sharedClient]
                                               dataOrStringToDictionary:responseObject];
                         
                         if (dict) {
                             
                             successBlock(dict,nil);
                         }
                         
                     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                         
                         errorBlock(error);
                     }];
}

#pragma mark - post请求
+ (void)postAsynchronous:(NSString *)path
               parameter:(id)dic
            successBlock:(HTTPRequestFinishingHandler)successBlock
              errorBlock:(HTTPRequestFailedHandler)errorBlock {
    
    [[self sharedClient] POST:path parameters:dic progress:nil
                      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                          
                          NSDictionary *dict = [[self sharedClient]
                                                dataOrStringToDictionary:responseObject];
                          
                          if (dict)
                          {
                              successBlock(dict,nil);
                              return ;
                          }
                          
                          NSString *str = [[self sharedClient]
                                           dataTOjsonString:responseObject];
                          
                          if (![str isEqualToString:@""]&& str !=nil) {
                              NSDictionary *dict = @{@"data":str};
                              successBlock(dict,nil);
                              return;
                          }
                          
                          NSDictionary *dictToDict =  [[self sharedClient]
                                                       dataToDictionary:responseObject];
                          if (dictToDict)
                          {
                              successBlock(dictToDict,nil);
                              return ;
                          } else {
                              errorBlock(nil);
                          }
                          
                      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                          errorBlock(error);
                      }];
}

#pragma mark - put请求
+ (void)putAsynchronous:(NSString *)path
              parameter:(id)dic
           successBlock:(HTTPRequestFinishingHandler)successBlock
             errorBlock:(HTTPRequestFailedHandler) errorBlock{
    
    
    [[self sharedClient] PUT:path parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [[self sharedClient]
                              dataOrStringToDictionary:responseObject];
        if (dict)
        {
            successBlock(dict,nil);
        } else {
            errorBlock(nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
    }];
    
}

- (NSDictionary *)dataOrStringToDictionary:(id)object {
    
    if ([object isKindOfClass:[NSData class]]) {
        
        return [self dataToDictionary:object];
        
    }else if ([object isKindOfClass:[NSString class]]) {
        
        NSData *data = [object dataUsingEncoding:NSUTF8StringEncoding];
        
        return [self dataToDictionary:data];
        
    }else if ([object isKindOfClass:[NSDictionary class]]) {
        
        return (NSDictionary *)object;
    }
    
    return nil;
}

- (NSDictionary *)dataToDictionary:(NSData *)date {
    
    NSError *error = nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:date
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error];
    return dict;
}

//用于字典等转字符串
+ (NSString *)dataTOjsonString:(id)object;
{
    
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if ( !jsonData ) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

//用于人脸注册
+ (void) upload:(NSString *)path
          image:(UIImage *)data
   successBlock:(HTTPRequestFinishingHandler)successBlock
     errorBlock:(HTTPRequestFailedHandler) errorBlock {
    
    [[self sharedClient] POST:path
                   parameters:nil
    constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData =  UIImageJPEGRepresentation(data, 0.1);
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
        //                 [formData appendPartWithFileData:data name:@"file" fileName:@"file" mimeType:@"File"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%f",uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [[self sharedClient]
                              dataOrStringToDictionary:responseObject];
        if (dict)
        {
            successBlock(dict,nil);
        } else {
            errorBlock(nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
    }];
}

//用于人脸检测，上传用户名和活体数据
+ (void) upload:(NSString *)path image:(UIImage *) image andLiveData:(NSData *)data
   successBlock:(HTTPRequestFinishingHandler)successBlock
     errorBlock:(HTTPRequestFailedHandler) errorBlock{
    
    [[self sharedClient] POST:path
                   parameters:nil
    constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData =  UIImageJPEGRepresentation(image, 0.1);
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
        [formData appendPartWithFileData:data name:@"livedata" fileName:@"livedata" mimeType:@"File"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%f",uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [[self sharedClient]
                              dataOrStringToDictionary:responseObject];
        if (dict)
        {
            successBlock(dict,nil);
        } else {
            errorBlock(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
    }];
}

//上传音频文件，用于原生
+ (void) uploadAudioFile:(NSString *)path
                  params:(NSDictionary*)params
                    data:(NSData *)data
            successBlock:(HTTPRequestFinishingHandler)successBlock
              errorBlock:(HTTPRequestFailedHandler) errorBlock {
    
    [[self sharedClient] POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSString *pathUrl = [params objectForKey:@"path"];
        NSString *fileName = [[pathUrl componentsSeparatedByString:@"/"] lastObject];
        [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%@",fileName] mimeType:@"wav"];
        
        // [formData appendPartWithFileURL:[NSURL fileURLWithPath:pathUrl] name:[NSString stringWithFormat:@"%@.wav",pathUrl] error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%f",uploadProgress.fractionCompleted);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [[self sharedClient]
                              dataOrStringToDictionary:responseObject];
        if (dict)
        {
            successBlock(dict,nil);
        } else {
            errorBlock(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
    }];
}
+ (void) uploadFaceFile:(NSString *)path
                 params:(NSDictionary*)params
                   data:(UIImage *)data
           successBlock:(HTTPRequestFinishingHandler)successBlock
             errorBlock:(HTTPRequestFailedHandler) errorBlock {
    
    [[self sharedClient] POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
//        NSString *pathUrl = [params objectForKey:@"path"];
//        NSString *fileName = [[pathUrl componentsSeparatedByString:@"/"] lastObject];
        //        [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%@",fileName] mimeType:@"audio/wav"];
        NSData *imageData =  UIImageJPEGRepresentation(data, 0.1);
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
        // [formData appendPartWithFileURL:[NSURL fileURLWithPath:pathUrl] name:[NSString stringWithFormat:@"%@.wav",pathUrl] error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%f",uploadProgress.fractionCompleted);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [[self sharedClient]
                              dataOrStringToDictionary:responseObject];
        if (dict)
        {
            successBlock(dict,nil);
        } else {
            errorBlock(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
    }];
}
//sensetime 上传文件
+ (void) upload:(NSString *)path
      imageFile:(UIImage *)data
   successBlock:(HTTPRequestFinishingHandler)successBlock
     errorBlock:(HTTPRequestFailedHandler) errorBlock {
    
    [[self sharedSenseTimeClient] POST:@"https://v2-auth-api.visioncloudapi.com/resource/image/file"
                            parameters:nil
             constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                 
                 NSData *imageData =  UIImageJPEGRepresentation(data, 0.1);
                 [formData appendPartWithFileData:imageData name:@"data" fileName:@"image_file.jpg" mimeType:@"image/jpeg"];
                 
             } progress:^(NSProgress * _Nonnull uploadProgress) {
                 NSLog(@"%f",uploadProgress.fractionCompleted);
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSDictionary *dict = (NSDictionary *)responseObject;
                 if( ([[dict objectForKey:@"code"] integerValue] == 1000)){
                     successBlock(dict,nil);
                 }else {
                     errorBlock(nil);
                 }
                 //
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 errorBlock(error);
             }];
}

//sensetime 用于上传
+ (void) postImage:(NSString *)path image:(UIImage *) image data:(NSData *)data
      successBlock:(HTTPRequestFinishingHandler)successBlock
        errorBlock:(HTTPRequestFailedHandler) errorBlock{
    //https://v2-auth-api.visioncloudapi.com/identity/image_verification/stateless
    // [[self sharedClient] POST:@"https://v2-auth-api.visioncloudapi.com/identity/liveness_image_verification/stateless"parameters:nil
    //       [formData appendPartWithFileData:imageData name:@"image_file" fileName:@"head.jpeg" mimeType:@"image/jpeg"];
    //         [formData appendPartWithFileData:imageData name:@"liveness_file" fileName:@"liveness_file" mimeType:@"File"];
    
    //        NSData *imageData =  UIImageJPEGRepresentation(image[0], 0.1);
    //        NSData *imageData1 =  UIImageJPEGRepresentation(image[1], 0.1);
    //
    //        [formData appendPartWithFileData:imageData name:@"first_image_file" fileName:@"first.jpeg" mimeType:@"image/jpeg"];
    //        [formData appendPartWithFileData:imageData1 name:@"second_image_file" fileName:@"second.jpeg" mimeType:@"image/jpeg"];
    
    //    [[self sharedSenseTimeClient] POST:@"https://v2-auth-api.visioncloudapi.com/identity/liveness_image_verification/stateless"
    
    [[self sharedSenseTimeClient] POST:path
                            parameters:nil
             constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                 
                 NSData *imageData =  UIImageJPEGRepresentation(image, 0.1);
                 [formData appendPartWithFileData:imageData name:@"image_file" fileName:@"head.jpeg" mimeType:@"image/jpeg"];
                 [formData appendPartWithFileData:data name:@"liveness_file" fileName:@"liveness_file" mimeType:@"File"];
                 
             } progress:^(NSProgress * _Nonnull uploadProgress) {
                 NSLog(@"%f",uploadProgress.fractionCompleted);
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSDictionary *dict = (NSDictionary *)responseObject;
                 if( ([[dict objectForKey:@"code"] integerValue] == 1000)){
                     successBlock(dict,nil);
                 }else {
                     errorBlock(nil);
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 errorBlock(error);
             }];
}

@end
